package com.tg.base.concurrent.future;

import com.tg.base.concurrent.SlowAction;

import java.util.concurrent.*;

public class FutureTaskCancelFalse {

    private static final Integer LOCK = 0;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Executor executor = Executors.newFixedThreadPool(1);

        FutureTask<Integer> taskA = buildFuture("thread a");
        FutureTask<Integer> taskB = buildFuture("thread b");


        executor.execute(taskA);
        //挂起30毫秒，保证task a先run
        TimeUnit.MILLISECONDS.sleep(30);

        executor.execute(taskB);

        //cancel a：不成功，task A已经执行
        taskA.cancel(false);
        //cancel b：当任务a仍然执行中，task b为NEW状态，cancel成功
//        taskB.cancel(false);
        System.out.println("thread a:cancel");

        TimeUnit.SECONDS.sleep(10);
    }

    private static FutureTask<Integer> buildFuture(String name) {
        return new FutureTask<Integer>(() -> {
            System.out.println(name + ":running");


            SlowAction.invoke();
            System.out.println(name + ":done");
            return 1;
        });
    }
}
